package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.form.OrderDetail;
import com.cskaoyan.order.service.OrderQueryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wjs
 * @ClassName OrderQueryServiceImpl
 * @Description 创建日期: 2022/6/18 15:03
 */
@Slf4j
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderConverter orderConverter;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;


    @Override
    public OrderWithDetailResponse orderList(OrderListRequest request) {
        OrderWithDetailResponse response = new OrderWithDetailResponse();
        try {
            //参数校验
            request.requestCheck();

            //查询数据库所有订单
            //开启分页
            PageHelper.startPage(request.getPage(), request.getSize());
            Example orderExample = new Example(Order.class);
            Example.Criteria criteria = orderExample.createCriteria();
            criteria.andEqualTo(OrderConstants.ORDER_USER_ID, request.getUserId());
            criteria.andNotEqualTo(OrderConstants.ORDER_STATUS,OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
            criteria.andNotEqualTo(OrderConstants.ORDER_STATUS,OrderConstants.ORDER_STATUS_TRANSACTION_DELETE);
            orderExample.setOrderByClause(OrderConstants.ORDER_DEFAULT_SORT_RULE);
            List<Order> orderList = orderMapper.selectByExample(orderExample);
            PageInfo pageInfo = new PageInfo(orderList);

            response.setTotal(pageInfo.getTotal());

            //对象转换与封装
            List<OrderDetailInfo> detailInfoList = new ArrayList<>();
            for (Order order : orderList) {
                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);
                //查询order对应的item
                List<OrderItem> orderItems = orderItemMapper.queryByOrderId(order.getOrderId());
                List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);

                orderDetailInfo.setOrderItemDto(orderItemDtos);

                //查询收货信息
                Example orderShippingExample = new Example(OrderShipping.class);
                orderShippingExample.createCriteria().andEqualTo(OrderConstants.ID_ORDER, order.getOrderId());
                List<OrderShipping> orderShippings = orderShippingMapper.selectByExample(orderShippingExample);
                if (orderShippings != null && orderShippings.size() != 0) {
                    OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShippings.get(0));

                    orderDetailInfo.setOrderShippingDto(orderShippingDto);
                }
                detailInfoList.add(orderDetailInfo);
            }
            response.setData(detailInfoList);
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.orderList occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public OrderDetailResponse orderDetail(OrderDetailRequest request) {
        OrderDetailResponse response = new OrderDetailResponse();
        try {
            request.requestCheck();
            OrderDetail orderDetail = new OrderDetail();
            //先从订单中获取用户id，订单状态 订单总金额
            Order order = orderMapper.selectByPrimaryKey(request.getOrderId());
            orderDetail.setUserId(orderDetail.getUserId());
            orderDetail.setOrderStatus(order.getStatus());
            orderDetail.setOrderTotal(order.getPayment());

            //从收获信息表获取收货人，电话，地址
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(request.getOrderId());
            orderDetail.setUserName(orderShipping.getReceiverName());
            orderDetail.setTel(orderShipping.getReceiverPhone());
            //TODO 优化点
            orderDetail.setStreetName(orderShipping.getReceiverAddress());

            //获取订单中的商品信息
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo(OrderConstants.ID_ORDER,request.getOrderId());
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);

            orderDetail.setGoodsList(orderItemDtos);
            response.setOrderDetail(orderDetail);
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());


        }catch (Exception e){
            log.error("OrderQueryServiceImpl.orderDetail occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest deleteOrderRequest) {
        DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
        try {
            deleteOrderRequest.requestCheck();
            Order order = new Order();
            order.setOrderId(deleteOrderRequest.getOrderId());
            order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_DELETE);
            orderMapper.updateByPrimaryKeySelective(order);
            deleteOrderResponse.setCode(OrderConstants.ORDER_DELETE_SUCCESS);
            deleteOrderResponse.setMsg(OrderConstants.ORDER_CREATE_SUCCESS);
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(deleteOrderResponse,e);
        }
        return deleteOrderResponse;
    }
}